﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;

namespace MazeWars
{
    class SoundManager
    {
        static SoundManager inst;
        AudioEngine engine;
        SoundBank[] sb;
        WaveBank[] wb;
        List<Cue> cue;

        const int NUM_SOUND_BANKS = 1;
        const int NUM_WAVE_BANKS = 1;

        public SoundManager()
        {
            engine = new AudioEngine(@"Content\Audio\XACT2.xgs");
            sb = new SoundBank[NUM_SOUND_BANKS];
            sb[0] = new SoundBank(engine, @"Content\Audio\TutorialSoundBank.xsb");

            wb = new WaveBank[NUM_WAVE_BANKS];
            wb[0] = new WaveBank(engine, @"Content\Audio\TutorialWaveBank.xwb", 0, 4);

            cue = new List<Cue>();
            engine.Update();
        }

        public void PlayCue(int sbNum, string cueName)
        {
            Cue newCue = sb[sbNum].GetCue(cueName);
            newCue.Play();
            cue.Add(newCue);
        }

        public void StopCue(string cueName)
        {
            foreach (Cue c in cue)
            {
                if (c.Name == cueName && c.IsPlaying)
                {
                    c.Stop(AudioStopOptions.Immediate);
                }
            }
        }

        public void Update()
        {
            engine.Update();
            if (cue.Count > 0)
            {
                for (int i = 0; i < cue.Count; i++)
                {
                    if (cue[i].IsStopped)
                    {
                        cue.RemoveAt(i);
                    }
                }
            }
        }

        public void Shutdown()
        {
            foreach (Cue c in cue)
            {
                if (c.IsPlaying)
                {
                    c.Stop(AudioStopOptions.Immediate);
                }
            }
        }

        public bool IsPlaying(string name)
        {
            foreach (Cue c in cue)
            {
                if (c.Name == name)
                {
                    return true;
                }
            }
            return false;
        }

        static public SoundManager Instance()
        {
            if (inst == null)
                inst = new SoundManager();
            return inst;
        }
    }
}
